package com.simen.android.mergeaar.core;

import com.simen.android.mergeaar.core.model.RemoteUrlRes;
import com.simen.hellobytes.IOUtil;
import com.simen.hellobytes.interfaces.LineIterator;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * author: SimenHi
 * create time: 2020-06-03 17:05
 * description:
 */
public class Config {

    List<String> repositories = new ArrayList<String>();
    List<String> dependencies = new ArrayList<String>();
    Map<String, String> dependenciesMap = new HashMap<String, String>();
    Map<String, RemoteUrlRes> remoteUrlResMap=new HashMap<String, RemoteUrlRes>();

    public void parse(String file) throws IOException {
        IOUtil.iteratorFileLine(new File(file), new LineIterator() {
            public void onRead(String line) throws IOException {
                if (!line.startsWith("#")) {
                    String trimLine = line.trim();
                    if (trimLine.startsWith("url") || trimLine.startsWith("jar") || trimLine.startsWith("aar") || trimLine.startsWith("repository")) {
                        int equalIndex = trimLine.indexOf("=");
                        if (equalIndex != -1) {
                            String[] args = trimLine.split("=");

                            args[0] = args[0].trim();
                            args[1] = args[1].trim();
                            if (args[1].contains("#")) {
                                args[1] = args[1].substring(0, args[1].indexOf("#"));
                            }

                            args[1] = args[1].replaceAll("\"", "").replaceAll("\'", "").trim();

                            if("repository".equals(args[0])){
                                repositories.add(args[1]);
                            }else {
                                if("url".equals(args[0])){
                                    parseRemoteUrlRes(args[1]);
                                }
                                dependencies.add(args[1]);
                                dependenciesMap.put(args[1], args[0]);
                            }
                        }
                    }
                }
            }
        });
    }

    private void parseRemoteUrlRes(String remoteUrlRes) {
        String[] array=remoteUrlRes.split(":");

        remoteUrlResMap.put(remoteUrlRes,new RemoteUrlRes(array[0],array[1],array[2]));
    }

    public List<String> getDependencies() {
        return dependencies;
    }

    public Map<String, String> getDependenciesMap() {
        return dependenciesMap;
    }

    public Map<String, RemoteUrlRes> getRemoteUrlResMap() {
        return remoteUrlResMap;
    }
}
